package server;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import ioc.BeanFactory;
import web.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class MyHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String method = exchange.getRequestMethod();
        String path = exchange.getRequestURI().getPath();
        String query = exchange.getRequestURI().getQuery();
        Map<String, String> queryParams = QueryParser.parseQueryString(query);

        // 读取请求体
        InputStream is = exchange.getRequestBody();
        StringBuilder sb = new StringBuilder();
        int b;
        while ((b = is.read()) != -1) {
            sb.append((char) b);
        }
        String body = sb.toString();

        Request request = new Request(method, path, queryParams, body);
        System.out.println(request);
        excute(request, exchange);
    }

    private void excute(Request request, HttpExchange exchange) throws IOException {
        HttpApp httpApp = (HttpApp) BeanFactory.get("app");
        httpApp.init();
        if (request.getPath().startsWith(httpApp.getContext())) {
            HttpService httpService = httpApp.getHttpService(request.getPath());
            if (httpService != null) {
                if ("GET".equalsIgnoreCase(request.getMethod())) {
                    Response response = new Response(200, "", "text/plain");
                    httpService.doGet(request, response);
                    sendResponse(exchange, response);
                } else {
                    Response response = new Response(200, "", "text/plain");
                    httpService.doPost(request, response);
                    sendResponse(exchange, response);
                }

            } else {
                sendResponse(exchange, new Response(404, "servcie Not found", "text/plain"));
            }
        } else {
            sendResponse(exchange, new Response(404, "app Not found", "text/plain"));
        }

    }


    private void sendResponse(HttpExchange exchange, Response response) throws IOException {
        byte[] responseBytes = response.getBody().getBytes(StandardCharsets.UTF_8);
        exchange.getResponseHeaders().set("Content-Type", response.getContentType());
        exchange.sendResponseHeaders(response.getStatusCode(), responseBytes.length);

        try (OutputStream os = exchange.getResponseBody()) {
            os.write(responseBytes);
        }
    }
}